<template>
    <div>
        <el-dialog
            :title="title"
            :visible.sync="open"
            width="1200px"
            append-to-body
            :before-close="cancel"
            :close-on-click-modal="false"
        >
            <el-form
                :model="queryParams"
                ref="queryForm"
                size="small"
                :inline="true"
                v-show="showSearch"
                label-width="68px"
            >
                <el-form-item label="姓名" prop="realName">
                    <el-input
                        v-model="queryParams.realName"
                        placeholder="请输入姓名"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="部门" prop="deptId">
                    <treeselect
                        v-model="queryParams.deptId"
                        :options="deptOptions"
                        :show-count="true"
                        placeholder="请选择部门"
                        @keyup.enter.native="handleQuery"
                        style="width: 215px"
                    />
                </el-form-item>
                <el-form-item label="岗位" prop="postId">
                    <el-select
                        v-model="queryParams.postId"
                        placeholder="请选择岗位"
                        clearable
                    >
                        <el-option
                            v-for="item in postList"
                            :key="item.postId"
                            :label="item.postName"
                            :value="item.postId"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="状态" prop="staffType">
                    <el-select
                        v-model="queryParams.staffType"
                        placeholder="请选择状态"
                        clearable
                    >
                        <el-option
                            v-for="dict in dict.type.hrm_staff_type"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                        />
                    </el-select>
                </el-form-item> -->

                <el-form-item>
                    <el-button
                        type="primary"
                        icon="el-icon-search"
                        size="mini"
                        @click="handleQuery"
                        >查询</el-button
                    >
                    <el-button
                        icon="el-icon-refresh"
                        size="mini"
                        @click="resetQuery"
                        >重置</el-button
                    >
                </el-form-item>
            </el-form>
            <TableCard>
                <el-table
                    :border="Global.tableShowBorder"
                    v-loading="loading"
                    :data="inductionList"
                    @row-click="handleRowClick"
                    @selection-change="handleSelectionChange"
                    highlight-current-row
                >
                    <!-- <el-table-column
                        type="selection"
                        width="55"
                        align="center"
                    /> -->
                    <el-table-column
                        type="index"
                        label="序号"
                        width="55"
                        align="center"
                    />
                    <el-table-column
                        label="姓名"
                        align="center"
                        prop="realName"
                    />
                    <el-table-column label="性别" align="center" prop="sex">
                        <template slot-scope="scope">
                            <dict-tag
                                v-if="scope.row.sex"
                                :options="dict.type.sys_user_sex"
                                :value="scope.row.sex"
                            ></dict-tag>
                            <span v-else>—</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="部门名称"
                        align="center"
                        prop="deptId"
                    >
                        <template slot-scope="scope">
                            <span>{{ parseSelectTree(scope.row.deptId) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="岗位名称"
                        align="center"
                        prop="postId"
                    >
                        <template slot-scope="scope">
                            <span>{{ parsePostName(scope.row.postId) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="员工状态"
                        align="center"
                        prop="staffType"
                    >
                        <template slot-scope="scope">
                            <dict-tag
                                :options="dict.type.hrm_staff_type"
                                :value="scope.row.staffType"
                            />
                        </template>
                    </el-table-column>
                </el-table>

                <pagination
                    v-show="total > 0"
                    :total="total"
                    :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize"
                    @pagination="getList"
                />
            </TableCard>

            <span slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="confirm">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {
    listInduction,
    getInduction,
    delInduction,
    addInduction,
    updateInduction,
    createUser,
} from "@/api/hrm/staff/induction";
import { cancleFlow, submitFlow } from "@/api/workflow/processInstance";
import FlowInfo from "@/views/workflow/flow/flowInfo";
import BillType from "@/billType";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listPostAll } from "@/api/system/post";
import { mapState, mapGetters, mapMutations } from "vuex";

const defaultQueryParams = {
    deptId: null,
    postId: null,
    staffType: null,
    pageNum: 1,
    pageSize: 10,
    orderByColumn: "",
    isAsc: "descending",
    realName: null,
    sex: null,
    nation: null,
    birthdate: null,
    political: undefined,
    joinpartyDate: null,
    marryStatus: null,
    height: null,
    weight: null,
    nativePlace: null,
    idNum: null,
    phone: null,
    mail: null,
    driverslicenseType: null,
    englishLevel: null,
};
export default {
    dicts: [
        "political_status",
        "education_list",
        "nation_list",
        "marry_status",
        "language_level",
        "sys_user_sex",
        "driverslicense_type",
        "hrm_staff_type",
        "hrm_staff_type",
    ],
    components: { Treeselect },
    name: "tableDialog",
    watch: {
        open(val) {
            if (val) {
                //初始化表格
                this.resetQuery();
            }
        },
    },
    props: {
        title: {
            type: String,
            default: "选择员工",
        },
        open: {
            type: Boolean,
            default: false,
        },
        tableData: {
            type: Array,
            default: () => [],
        },
        defaultParams: {
            type: Object,
            default: () => {},
        },
    },
    data() {
        return {
            queryParams: {
                ...this.defaultParams,
                ...defaultQueryParams,
            },
            billType: BillType.billType.STAFF_INDUCTION,
            showFlowInfo: false,
            businessId: null,
            // 部门树选项
            deptOptions: [],
            // 职位选项
            postList: [],
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 子表选中数据
            checkedPlStaffInductionEduexp: [],
            // 非单个禁用
            single: false,
            // 非多个禁用
            multiple: false,
            // 显示查询条件
            showSearch: true,
            // 总条数
            total: 0,
            // 员工入职表格数据
            inductionList: [],
            // 员工入职信息登记--教育经历表格数据
            staffInductionEduexpList: [],

            // 表单参数
            form: {},
            // 表单校验
            rules: {},
            //存储拍平后的selectTree数据
            deptOptionsArray: null,
            chosenObj: null, //选中的对象
            isRowSelected: false,
            selection: [],
        };
    },
    computed: {
        matchPostId() {
            return this.postList.find((item) => item.id === this.postId);
        },
    },
    created() {
        // this.getList();
        //查询基础数据
        this.getTreeselect();
        this.getPostList();
    },
    methods: {
        handleRowClick(value) {
            this.selection = [{ value }];
        },
        // 如果需要重置颜色，可以在这里重置

        /** 查询员工入职列表 */
        getList() {
            this.loading = true;
            this.queryParams.params = {};
            this.queryParams.params["order"] = 1;
            listInduction(this.queryParams).then((response) => {
                this.inductionList = response.rows;
                this.total = response.total;
                this.loading = false;
                console.log(response);
            });
        },
        confirm() {
            if (this.selection.length < 1) {
                this.$message.error("请选择员工");
            } else {
                this.$emit("update:open", false);
                this.$emit("confirm", this.selection[0].value);
            }
        },
        cancel() {
            this.$emit("update:open", false);
        },

        ...mapMutations("staffViewBook", ["setSearchCache"]),
        parseSelectTree(id) {
            let tempObj = this.deptOptionsArray.find((item) => item.id == id);
            if (tempObj) {
                return tempObj.label;
            }
            return "—";
        },
        flattenArray(arr) {
            let result = [];
            for (let i = 0; i < arr.length; i++) {
                let item = arr[i];
                result.push(item);
                if (item.children) {
                    result = result.concat(this.flattenArray(item.children));
                }
            }
            return result;
        },

        parsePostName(ids) {
            if (!ids) {
                return "—";
            }
            if (ids != null && ids != "") {
                let nameArr = [];
                let selIds = ids.split(",");
                this.postList.forEach((item) => {
                    selIds.forEach((sel) => {
                        if (item.postId == sel) {
                            nameArr.push(item.postName);
                        }
                    });
                });
                return nameArr.join(",");
            }
        },
        getPostList() {
            listPostAll().then((res) => {
                this.postList = res.data;
            });
        },
        /** 查询部门下拉树结构 */
        getTreeselect() {
            treeselect().then((response) => {
                this.deptOptions = response.data;
                console.log(this.deptOptions, "this.deptOptions");

                this.deptOptionsArray = this.flattenArray(this.deptOptions);
                console.log(this.deptOptionsArray, " this.deptOptionsArray ");
            });
        },
        /** 查询员工入职列表 */
        getList() {
            this.loading = true;
            this.queryParams.params = {};
            this.queryParams.params["order"] = 1;
            listInduction(this.queryParams).then((response) => {
                this.inductionList = response.rows;
                this.total = response.total;
                this.loading = false;
                console.log(response);
            });
        },
        /** 查询按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;

            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            // this.resetForm("queryForm");
            this.selection = [];
            this.queryParams = { ...defaultQueryParams, ...this.defaultParams };

            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.$tab.openPage(
                "员工入职登记信息表",
                "/hrm/staff/induction/form/add"
            );
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            const id = row.id || this.ids;
            // this.$tab.openPage("员工入职登记信息表", "/hrm/staff/book/form/"+id);
            this.$router.push({
                path: "/hrm/staff/book/form/" + row.id,
                query: { readonly: "0" },
            });
        },

        /** 员工创建系统用户 **/
        createUser(row) {
            this.$modal.confirm("确认创建系统用户？").then(() => {
                return createUser(row.id).then((res) => {
                    if (200 == res.code) {
                        this.$modal.msgSuccess("创建用户成功");
                    }
                });
            });
        },
        /** 查看单据详情 */
        handleView(row) {
            this.$router.push({
                path: "/hrm/staff/book/form/" + row.id,
                query: { readonly: "1" },
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal
                .confirm('是否确认删除员工入职编号为"' + ids + '"的数据项？')
                .then(function () {
                    return delInduction(ids);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                })
                .catch(() => {});
        },
        /** 员工入职信息登记--教育经历序号 */
        rowPlStaffInductionEduexpIndex({ row, rowIndex }) {
            row.index = rowIndex + 1;
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                "hrm/staff/induction/export",
                {
                    ...this.queryParams,
                },
                `induction_${new Date().getTime()}.xlsx`
            );
        },

        /** 提交审批 ***/
        doSubmitFlow(row) {
            let data = {
                businessId: row.id,
                billType: BillType.billType.STAFF_INDUCTION,
            };
            this.$modal
                .confirm("确认要提交该单据进行审批吗？")
                .then(() => {
                    return submitFlow(data);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("提交成功");
                })
                .catch(() => {});
        },
        /** 取回审批 ***/
        doCancleFlow(row) {
            let data = {
                businessId: row.id,
                billType: BillType.billType.STAFF_INDUCTION,
            };
            this.$modal.confirm("确认要取回该协议审批吗？").then(() => {
                cancleFlow(data).then((res) => {
                    if (200 == res.code) {
                        this.getList();
                        this.$modal.msgSuccess("取回成功");
                    }
                });
            });
        },
        /** 流程信息 ***/
        flowDetail(row) {
            this.businessId = row.id + "";
            this.showFlowInfo = true;
        },
        //关闭流程信息窗口
        closeFlowInfoDialog() {
            this.showFlowInfo = false;
        },
    },
};
</script>

<style lang="scss" scoped></style>
